//
//  AppDelegate.m
//  MeterMart
//
//  Created by ENERGY on 2018/9/16.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "AppDelegate.h"
#import "MainViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "WZXLaunchViewController.h"
#import "ViewController.h"
#import "WebViewController.h"
#import "MessageViewController.h"

// 引入 JPush 功能所需头文件
#import "JPUSHService.h"
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用 idfa 功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>

@interface AppDelegate ()<WXApiDelegate, JPUSHRegisterDelegate>
@property (nonatomic, assign)BOOL APPFromBackGround;//判断是从杀死程序的情况打开还是在运行当中打开
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //实例化
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    //背景颜色
    self.window.backgroundColor = [UIColor whiteColor];
    //设置app属性
    [self setupAppStyle];
    //主视图
//    MainViewController *mainVc = [[MainViewController alloc] init];
//    [self.window setRootViewController:mainVc];
    //向微信注册
    [WXApi registerApp:@"wxd2bcf02d510e02f4"];
    // 启动图片延时: 1秒
//    [NSThread sleepForTimeInterval:3];
    self.APPFromBackGround = NO;//刚运行时当做是未打开状态，在打开之后变为YES
    //设置启动页
    [WZXLaunchViewController showWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height-150) ImageURL:@"http://yimi.sencant.com/public/images/start.jpg" advertisingURL:nil timeSecond:3 hideSkip:YES imageLoadGood:^(UIImage *image, NSString *imageURL) {
        // 广告加载结束
        NSLog(@"%@ %@",image,imageURL);
        
    } clickImage:^(UIViewController *WZXlaunchVC){
        /// 点击广告
        //2.在webview中打开
        MainViewController *mainVc = [[MainViewController alloc] init];
        [self.window setRootViewController:mainVc];
    } theAdEnds:^{
        if (self.APPFromBackGround == NO) {
            //广告展示完成回调,设置window根控制器
            MainViewController *mainVc = [[MainViewController alloc] init];
            [self.window setRootViewController:mainVc];
        }
    }];
    
    //Required
    //notice: 3.0.0 及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义 categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // Optional
    // 获取 IDFA
    // 如需使用 IDFA 功能请添加此代码并在初始化方法的 advertisingIdentifier 参数中填写对应值
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
    // init Push
    // notice: 2.1.5 版本的 SDK 新增的注册方法，改成可上报 IDFA，如果没有使用 IDFA 直接传 nil
    // 如需继续使用 pushConfig.plist 文件声明 appKey 等配置内容，请依旧使用 [JPUSHService setupWithOption:launchOptions] 方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@"3b97e7f5499d7347ddf577f5"
                          channel:@"App Store"
                 apsForProduction:1
            advertisingIdentifier:advertisingId];
    return YES;
}

//设置app属性
- (void)setupAppStyle{
    //修改状态栏颜色 + plist文件
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    //    //设置nav title颜色
    //    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil];
    //    [UINavigationBar appearance].titleTextAttributes = attributes;
    //    //设置nav背景颜色
    ////    [UINavigationBar appearance].barTintColor = getColor(mainColor);
    //    [UINavigationBar appearance].barTintColor = getColor(mainColor);
    //设置tab title颜色
    [UITabBar appearance].tintColor = getColor(@"e72700");
    //    [UINavigationBar appearance].tintColor = [UIColor whiteColor];
    
    //设置背景颜色
    [UITabBar appearance].barTintColor = [UIColor whiteColor];
    // 去掉TabBar上边的线
    //    [[UITabBar appearance] setTranslucent:NO];
    //    [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
    //    [[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(nonnull NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
}

/**
 这里处理微信/支付宝支付完成之后跳转回来
 */
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    //如果极简 SDK 不可用,会跳转支付宝钱包进行支付,需要将支付宝钱包的支付结果回传给 SDK
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"支付宝客户端支付结果result = %@",resultDic);
            if (resultDic && [resultDic objectForKey:@"resultStatus"] && ([[resultDic objectForKey:@"resultStatus"] intValue] == 9000)) {
                // 发通知带出支付成功结果
                [[NSNotificationCenter defaultCenter] postNotificationName:ZLAliReturnSucceedPayNotification object:resultDic];
            } else {
                // 发通知带出支付失败结果
                [[NSNotificationCenter defaultCenter] postNotificationName:ZLAliReturnFailedPayNotification object:resultDic];
            }
        }];
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic){
            NSLog(@"支付宝网页版result = %@",resultDic);
            if (resultDic && [resultDic objectForKey:@"resultStatus"] && ([[resultDic objectForKey:@"resultStatus"] intValue] == 9000)) {
                // 发通知带出支付成功结果
                [[NSNotificationCenter defaultCenter] postNotificationName:ZLAliReturnSucceedPayNotification object:resultDic];
            } else {
                // 发通知带出支付失败结果
                [[NSNotificationCenter defaultCenter] postNotificationName:ZLAliReturnFailedPayNotification object:resultDic];
            }
        }];
    }
    if ([sourceApplication isEqualToString:@"com.apple.MobileSMS"]) {
        //微信网页登录
        BOOL succeed = [WXApi handleOpenURL:url delegate:self];
        return succeed;
    }
    return [WXApi handleOpenURL:url delegate:self];
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{
    //如果极简 SDK 不可用,会跳转支付宝钱包进行支付,需要将支付宝钱包的支付结果回传给 SDK
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"支付宝客户端支付结果result = %@",resultDic);
            if (resultDic && [resultDic objectForKey:@"resultStatus"] && ([[resultDic objectForKey:@"resultStatus"] intValue] == 9000)) {
                // 发通知带出支付成功结果
                [[NSNotificationCenter defaultCenter] postNotificationName:ZLAliReturnSucceedPayNotification object:resultDic];
            } else {
                // 发通知带出支付失败结果
                [[NSNotificationCenter defaultCenter] postNotificationName:ZLAliReturnFailedPayNotification object:resultDic];
            }
        }];
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic){
            NSLog(@"支付宝网页版result = %@",resultDic);
            if (resultDic && [resultDic objectForKey:@"resultStatus"] && ([[resultDic objectForKey:@"resultStatus"] intValue] == 9000)) {
                // 发通知带出支付成功结果
                [[NSNotificationCenter defaultCenter] postNotificationName:ZLAliReturnSucceedPayNotification object:resultDic];
            } else {
                // 发通知带出支付失败结果
                [[NSNotificationCenter defaultCenter] postNotificationName:ZLAliReturnFailedPayNotification object:resultDic];
            }
        }];
    }
    [WXApi handleOpenURL:url delegate:self];
    return YES;
}

- (void)onReq:(BaseReq*)req{
    if ([req isKindOfClass:[GetMessageFromWXReq class]]) {
        //微信终端向第三方程序请求提供内容的消息结构体
        [WXApi class];
//                if (self.wxDelegate
//                    && [self.wxDelegate respondsToSelector:@selector(WXApiUtilsDidRecvGetMessageReq:)]) {
//                    GetMessageFromWXReq *getMessageReq = (GetMessageFromWXReq *)req;
//                    [self.wxDelegate WXApiUtilsDidRecvGetMessageReq:getMessageReq];
//                }
    } else if ([req isKindOfClass:[ShowMessageFromWXReq class]]) {
        //微信通知第三方程序，要求第三方程序显示的消息结构体
    //            if (self.wxDelegate
    //                && [self.wxDelegate respondsToSelector:@selector(WXApiUtilsDidRecvShowMessageReq:)]) {
    //                ShowMessageFromWXReq *showMessageReq = (ShowMessageFromWXReq *)req;
    //                [self.wxDelegate WXApiUtilsDidRecvShowMessageReq:showMessageReq];
    //            }
    } else if ([req isKindOfClass:[LaunchFromWXReq class]]) {
        //微信终端打开第三方程序携带的消息结构体
        //        if (self.wxDelegate
        //            && [self.wxDelegate respondsToSelector:@selector(WXApiUtilsDidRecvLaunchFromWXReq:)]) {
        //            LaunchFromWXReq *launchReq = (LaunchFromWXReq *)req;
        //            [self.wxDelegate WXApiUtilsDidRecvLaunchFromWXReq:launchReq];
        //        }
    }
}

//微信回调方法
- (void)onResp:(BaseResp *)resp{
    NSLog(@"resp:%d", resp.errCode);
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        SendMessageToWXResp *sendResp = (SendMessageToWXResp *)resp;
        NSString *str = [NSString stringWithFormat:@"%d",sendResp.errCode];
        if ([str isEqualToString:@"0"]) {
            
        }else{
            UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"回调信息" message:str delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alertview show];
        }
    }
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp * rep = (SendAuthResp *)resp;
        if (rep.errCode == 0) {
            //微信登录成功
            [[NSNotificationCenter defaultCenter] postNotificationName:WXAuthorizationSuccess object:@{@"code":rep.code}];
        }
    }
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        NSString *payResoult = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
        switch (resp.errCode) {
            case 0:
            {
                payResoult = @"支付结果：成功！";
                NSDictionary *dict =@{@"key":@"2"};
                NSNotification *notification =[NSNotification notificationWithName:WeChatReturnSucceedPayNotification object:nil  userInfo:dict];
                [[NSNotificationCenter defaultCenter] postNotification:notification];
            }
                break;
            case -1:
                payResoult = @"支付结果：失败！";
                break;
            case -2:
            {
                payResoult = @"用户已经退出支付！";
                
            }
                break;
            default:
                payResoult = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                break;
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付结果" message:payResoult delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
}

//极光
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
#pragma mark- JPUSHRegisterDelegate

// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //从通知界面直接进入应用
        NSLog(@"从通知界面直接进入应用");
    }else{
        //从通知设置界面进入应用
        NSLog(@"从通知设置界面进入应用");
    }
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
    self.APPFromBackGround = YES;
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        if (self.APPFromBackGround == YES) {
            MainViewController *mainVc = [[MainViewController alloc] init];
            [self.window setRootViewController:mainVc];
        }
        WebViewController *ctl = [[WebViewController alloc] init];
        UINavigationController * Nav = [[UINavigationController alloc]initWithRootViewController:ctl];//这里加导航栏是因为我跳转的页面带导航栏，如果跳转的页面不带导航，那这句话请省去。
        [[self topViewController] presentViewController:Nav animated:YES completion:nil];
    }
    completionHandler();  // 系统要求执行这个方法
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required, For systems with less than or equal to iOS 6
    [JPUSHService handleRemoteNotification:userInfo];
}
#pragma mark   通过我下面的函数可以获取当前的controller
- (UIViewController*)topViewController{
    return [self topViewControllerWithRootViewController:self.window.rootViewController];
}
- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController{
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabBarController = (UITabBarController *)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
            } else if (rootViewController.presentedViewController) {
            UIViewController* presentedViewController = rootViewController.presentedViewController;
            return [self topViewControllerWithRootViewController:presentedViewController];
                } else {
                return rootViewController;
            }
}
@end
